﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.IO;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting;
using ConexionCliente;
using System.Runtime.Serialization.Formatters;
using System.Collections;

namespace Manager
{
    class ClientController
    {
        private Object mutex = null;

        public ClientController()
        {
        }

        public void IniciarServicio(Object mutex)
        {
            this.mutex = mutex;
            Thread th = new Thread(AtenderClientes);
            th.Start();
        }

        private void AtenderClientes()
        {
            IServicioCliente servicioRemoto;
            int numero = 0;
            foreach (ClientNode c in Manager.conf.Clientes)
            {
                servicioRemoto = new ServicioCliente();

                BinaryServerFormatterSinkProvider serverProv = new BinaryServerFormatterSinkProvider();
                serverProv.TypeFilterLevel = TypeFilterLevel.Full;
                //RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;
                serverProv.TypeFilterLevel = TypeFilterLevel.Full;

                numero++;
                IDictionary propBag = new Hashtable();
                propBag["port"] = c.Puerto;
                propBag["typeFilterLevel"] = TypeFilterLevel.Full;
                propBag["name"] = "ClientChannel"+numero;
                TcpChannel tcpChan = new TcpChannel(propBag, null, serverProv);
                ChannelServices.RegisterChannel(tcpChan, false);
                RemotingConfiguration.RegisterWellKnownServiceType(typeof(ServicioCliente), "Cliente", WellKnownObjectMode.Singleton);

                Console.WriteLine("Escuchando peticiones del cliente con ip "+c.Ip+" en el puerto " + c.Puerto+"..");
            }
        }

    }
}